import { Message } from 'element-ui';
import axios from 'axios';

axios.defaults.withCredentials = true;

// 请求超时处理
axios.interceptors.request.use(
  (config) => {
    // console.log("http config", config);
    return config;
  },
  () => {
    Message.error({ message: '请求超时!' });
  }
);

// 返回异常处理
axios.interceptors.response.use(
  (res) => {
    if (res.status && res.status === 200 && res.data.resp_code !== 200) {
      console.log(res);
      Message.warning({ message: res.data.resp_msg });
    }
    return res.data;
  },
  (err) => {
    if(axios.isCancel(err)) {
      console.log('Request canceled', err.message);
      return {
        data: {
          status: 'error'
        } };
    }
    let msg = '';
    if (err.response) {
      if (err.response.data) {
        msg = err.response.data.resp_msg;
      }
      switch (err.response.status) {
        case 400:
          if (!msg) {
            msg = '错误请求!';
          }
          break;
        case 401:
        case 403:
          msg = '权限不足，请联系管理员!';
          break;
        case 404:
          if (!msg) {
            msg = '服务器连接异常!';
          }
          break;
        case 500:
        case 503:
        case 504:
          msg = '服务器连接不上!';
          break;
        default:
          if (!msg) {
            msg = '未知错误!';
          }
          break;
      }
    } else {
      msg = '网络错误!';
    }
    Message.error({ message: msg });
    return {
      data: {
        status: 'error'
      }
    };
  }
);

// 格式化Url
const formatUrl = (url) => {
  var _url = url;
  if (!(_url.startsWith('http://') || _url.startsWith('https://'))) {
    _url = `/fzcpserver/${_url}`;
  }
  return _url;
};

// 拼接参数
const formatParams = (params) => {
  let ret = '';
  let paramsArr = Object.keys(params);
  for (let i = 0; i < paramsArr.length; i++) {
    let param = params[paramsArr[i]];
    if (param !== null && param !== undefined) {
      ret += encodeURIComponent(paramsArr[i]) + '=' + encodeURIComponent(param);
      if (i < paramsArr.length - 1) {
        ret += '&';
      }
    }
  }
  return ret;
};

// 判断是否是JSON请求
const isJsonRequest = (url) => {
  const jsonList = [
    '/fzcpserver/pwgh-ghsj-txfw/sbjhSave/saveJhsb',
    '/fzcpserver/pwgh-ghsj-txfw/sbjh/addEquips',
    '/fzcpserver/pwgh-ghsj-txfw/sbjh/addTjd',
    '/fzcpserver/pwgh-ghsj-txfw/sbjh/modifyEquips',
    '/fzcpserver/pwgh-ghsj-txfw/sbjh/removeEquips',
    '/fzcpserver/pwgh-ghsj-txfw/pattern/addEquips',
    '/fzcpserver/pwgh-ghsj-txfw/pattern/searchEquips'
  ];
  return jsonList.indexOf(url) > -1;
};
// GET请求
export const get = (url, params) => {
  var _params = params;
  if (Object.prototype.hasOwnProperty.call(_params, 'params')) {
    _params = _params.params;
  }
  let ret = formatParams(_params);
  var _url = url + '?' + ret;
  return axios({
    method: 'get',
    url: formatUrl(_url)
  });
};

// POST请求
export const post = (url, params) => {
  var _url = url;
  var cancelToken = null;
  if(params.cancelToken) {
    cancelToken = params.cancelToken;
  }
  let requestData = Object.prototype.hasOwnProperty.call(params, 'params') ? params.params : params;
  // 判断是否为json请求
  let isJson = isJsonRequest(_url);
  if (isJson) {
    if (Object.prototype.hasOwnProperty.call(params, 'params')) {
      _url = _url + '?' + formatParams(params.params);
    }
    if (Object.prototype.hasOwnProperty.call(params, 'data')) {
      requestData = params.data;
    }
  }
  return axios({
    method: 'post',
    url: formatUrl(_url),
    data: requestData,
    transformRequest: [
      function() {
        return isJson ? JSON.stringify(requestData) : formatParams(requestData);
      }
    ],
    headers: {
      'Content-Type': isJson ? 'application/json' : 'application/x-www-form-urlencoded'
    },
    cancelToken
  });
};

// 上传文件
export const uploadFile = async(url, params) => {
  var _url = url;
  let requestData = params;
  if (Object.prototype.hasOwnProperty.call(params, 'params')) {
    requestData = requestData.params;
  }
  console.log(requestData);
  let ret = formatParams(requestData);
  _url = _url + '?' + ret;
  return axios({
    method: 'post',
    url: formatUrl(_url),
    data: requestData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
};

// 判断是否是文件请求
const isFileRequest = (url) => {
  const fileList = [
    '/pwgh-ghsj-qyfw/dxfYdxxController/dxfFileUpload',
    '/pwgh-ghsj-ghfw/ghbg/uploadPicture'
  ];
  return fileList.indexOf(url) > -1;
};
// 自定义请求
export const request = (data) => {
  let methodType = data.method;
  if (methodType === 'get') {
    return get(data.url, data.params);
  } else if (methodType === 'post') {
    if (isFileRequest(data.url)) {
      return uploadFile(data.url, data.params);
    }
    return post(data.url, data.params);

  }
};

